
import {WSS_SERVER_URL} from '../config.js'
import store from "@/store/index.js"
import utils from '@/common/util.js'

let WebSocket={};
let id='';
if(uni.getStorageSync('userInfo')){
	id=uni.getStorageSync('userInfo').id;
}else{
	id=utils.getUuid(); 
}


let time=60*60*1000;

WebSocket.socketOpen = false;
WebSocket.socketMsgQueue = [];

// 判断socket是否已连接
WebSocket.checkSocketState=()=> {
	let _this = this;
	uni.sendSocketMessage({
		data: 'open',
		success: (res) => {  
			WebSocket.socketOpen=true;
			return;
		},
		fail: (err) => { // 未连接打开websocket连接	 
			WebSocket.socketOpen=false; 
			WebSocket.open();
			// if(!WebSocket.socketOpen){
			// 	WebSocket.open(); 
			// }
		}
	});
}, 

// 建立连接
WebSocket.open=()=>{ 
	uni.connectSocket({
		url: 'wss://'+WSS_SERVER_URL+'?id='+id,
		success: (res) => {  
			console.log(res+'链接成功')
		}
	});
	uni.onSocketOpen ((res)=> {  
		console.log(res+'打开成功')
		WebSocket.socketOpen = true;   
	});
	uni.onSocketError ((res)=>{ 
		WebSocket.socketOpen = false; 
	});
	WebSocket.onSocketMessage();

},

// 发送数据
WebSocket.sendSocketMessage=(msg)=> {
	if(WebSocket.socketOpen) {
		uni.sendSocketMessage({
		  data: msg
		});
	}else{
		WebSocket.socketMsgQueue.push(msg);
	}
},

WebSocket.onSocketMessage=()=>{  
	uni.onSocketMessage((res)=>{   		
		if(res.data){
			console.log(JSON.parse(res.data))
			store.dispatch('new_socket_data', JSON.parse(res.data))
		}
	}); 
},

// 重连
WebSocket.reConnect=()=> {
    let timer=60*60*1000; 
    timer = setTimeout(() => {
		WebSocket.socketOpen=false;
    },time)
  }
  
WebSocket.close=()=>{
	uni.closeSocket({
		code:1000,  
		reason:'App Hide'  
	})  
}



export default WebSocket